/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import { checkIsMobile } from '@base/utils';
import { InputNumber, InputNumberProps } from 'antd';
import classNames from 'classnames';
import { isFunction } from 'lodash';
import React from 'react';
import styles from './index.less';

interface InputNumberExtendProps extends InputNumberProps {}

const InputNumberExtend: React.FC<InputNumberExtendProps> = (props) => {
  const {
    disabled,
    className,
    step = 1,
    max = Number.MAX_SAFE_INTEGER,
    min = Number.MIN_SAFE_INTEGER,
    value,
    onChange,
  } = props;
  const rootCls = classNames(styles.inputNumber, className);
  const isMobile = checkIsMobile();

  const triggerChange = (v: string) => {
    if (isFunction(onChange)) {
      onChange(v);
    }
  };

  const disabledUp = 1 * (value as any) >= max;
  const disabledDown = 1 * (value as any) <= min;

  const upCls = classNames('ant-input-number-handler ant-input-number-handler-up', {
    ['ant-input-number-handler-up-disabled']: disabledUp,
  });
  const downCls = classNames('ant-input-number-handler ant-input-number-handler-down', {
    ['ant-input-number-handler-down-disabled']: disabledDown,
  });

  // 增加
  const handleClickUp = () => {
    if (disabledUp) return;
    triggerChange(`${1 * (value as any) + 1 * (step as any)}`);
  };
  // 减少
  const handleClickDown = () => {
    if (disabledDown) return;
    triggerChange(`${1 * (value as any) - 1 * (step as any)}`);
  };

  return (
    <InputNumber
      {...props}
      className={rootCls}
      addonAfter={
        <>
          {isMobile && !disabled ? (
            <div className='ant-input-number-handler-wrap'>
              <span className={upCls} onClick={handleClickUp} />
              <span className={downCls} onClick={handleClickDown} />
            </div>
          ) : null}
        </>
      }
    />
  );
};

export default InputNumberExtend;
